Reverse a Sub-list (medium)
We'll cover the following
Problem Statement #
Given the head of a LinkedList and two positions ‘p’ and ‘q’, reverse the LinkedList from position ‘p’ to ‘q’.
Try it yourself #
Try solving this question here:
Solution #
The problem follows the In-place Reversal of a LinkedList pattern. We can use a similar approach as discussed in Reverse a LinkedList. Here are the steps we need to follow:
- Skip the first
p-1
nodes, to reach the node at positionp
. - Remember the node at position
p-1
to be used later to connect with the reversed sub-list. - Next, reverse the nodes from
p
toq
using the same approach discussed in Reverse a LinkedList. - Connect the
p-1
andq+1
nodes to the reversed sub-list.
Code #
Here is what our algorithm will look like:
Time complexity #
The time complexity of our algorithm will be where ‘N’ is the total number of nodes in the LinkedList.
Space complexity #
We only used constant space, therefore, the space complexity of our algorithm is .
Similar Questions #
Problem 1: Reverse the first ‘k’ elements of a given LinkedList.
Solution: This problem can be easily converted to our parent problem; to reverse the first ‘k’ nodes of the list, we need to pass p=1
and q=k
.
Problem 2: Given a LinkedList with ‘n’ nodes, reverse it based on its size in the following way:
- If ‘n’ is even, reverse the list in a group of n/2 nodes.
- If n is odd, keep the middle node as it is, reverse the first ‘n/2’ nodes and reverse the last ‘n/2’ nodes.
Solution: When ‘n’ is even we can perform the following steps:
- Reverse first ‘n/2’ nodes:
head = reverse(head, 1, n/2)
- Reverse last ‘n/2’ nodes:
head = reverse(head, n/2 + 1, n)
When ‘n’ is odd, our algorithm will look like:
head = reverse(head, 1, n/2)
head = reverse(head, n/2 + 2, n)
Please note the function call in the second step. We’re skipping two elements as we will be skipping the middle element.